#include <unistd.h>
#include <iostream>
#include <ctime>
#include <string>
#include "Socket.hpp"
#include "Protocol.hpp"

char ops[] = "+-*/%";

//./ClientCal [ip] [port]
void Usage(std::string cmd)
{
    std::cout << "\n\tUsage:" << cmd << " [ip]" << " [port]\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3) {
        Usage(argv[0]);
        exit(0);
    }
    std::string ip = argv[1];
    int port = atoi(argv[2]);
    srand((unsigned int)time(nullptr));
    Sock sk;
    int fd = sk.Socket();
    sk.Connect(ip, port);

    int cnt = 1;
    while(cnt <= 20)
    {
        std::cout << "-----------" << "第 " << cnt << " 次测试" << "-----------" << std::endl;
        Request rq;
        rq._x = rand() % 20 + 1;
        rq._y = rand() % 20;
        // rq._y = 0;
        rq._op = ops[rand() % 5];
        std::string msg = rq.Serialization();
        std::string package;
        Encode(msg, &package);
        std::cout << "package sended:\n" << package << std::endl;
        ssize_t n = write(fd, package.c_str(), package.size());
        
        char inbuff[1024];
        n = read(fd, inbuff, sizeof(inbuff));
        if(n == 0) { break; }
        inbuff[n] = 0;
        std::string inPackage(inbuff);
        std::string inmsg;
        Decode(inPackage, &inmsg);
        Response rp;
        rp.Deserialization(inmsg);
        std::cout << "result msg recved:" << std::endl;
        std::cout << "code = " << rp._code << std::endl;
        std::cout << "result = " << rp._result << std::endl;
        ++cnt;
        std::cout << "==================================\n" << std::endl;
        
        sleep(1);
    }
    return 0;
}